;$(function () {
    //跳转至活动创建页面
    $(".proAddBtn").click(function () {
        let value = $(this).attr("lay-value");
        let url = "promotionChoose";
        let jsonData = [];	//构建json
        jsonData.push({"type": value});	//将传参放入json中
        pageSkipping(url, jsonData);
    });
    $("#addNewAgain").click(function () {
        window.location.reload();
    });
    $("#backToPromotionInfo").click(function () {
        window.location = "toPromotion";
    });
    $("body").on("focus", ".money2Check", function (event) {
        var obj = event.srcElement ? event.srcElement : event.target;
        var am = $(obj).parent().parent().find("input[name='promotionMoney1']");
        var amv = am.val();
        if (amv == "") {
            $(obj).blur();
            layer.tips("不能为空", am, {
                tips: [1, '#2B2B2B'],
                time: 2000
            });
            $(am).focus();
            return;
        }
    });
    layui.use(['form', 'laydate', 'table', 'element'], function () {
        var table = layui.table,
            form = layui.form,
            laydate = layui.laydate,
            element = layui.element;
        var nowDate = getNowAndFormatDate();
        var now = {};
        now[nowDate] = "今天";
        laydate.render({
            elem: '#promotionDate'
            , range: true
            , trigger: 'click'
            , mark: now
        });
        laydate.render({
            elem: '#promotionSearchDate'
            , range: true
            , trigger: 'click'
            , mark: now
        });
        laydate.render({
            elem: '#promotionTime'
            , type: 'time'
            , range: true
            , trigger: 'click'
            , mark: now
            , value: '00:00:00 - 23:59:59'
        });
        $(".promotionRuleAddBtn").click(function () {
            var clone = $(this).parent().clone(true);
            clone.children().last().remove();
            clone.append('<button type="button" class="layui-btn layui-btn-danger promotionRuleDelBtn">\n' +
                '                                        <i class="layui-icon">&#xe640;</i>删除\n' +
                '                                    </button>\n').appendTo("#ruleBody");
            form.render();
        });
        $("body").on("click", ".promotionRuleDelBtn", function () {
            $(this).closest('.layui-inline').remove();
            form.render();
        });
        form.on('submit(promotionCreateForm)', function () {
            let promotionType = $("#promotionCreateTable").attr("lay-value");
            let promotionMoney1List = $("#ruleBody [name='promotionMoney1']");
            for (let i = 0; i < promotionMoney1List.length; i++) {
                let promotionMoney1 = $(promotionMoney1List[i]);
                let promotionMoney2 = promotionMoney1.parent().parent().find("input[name='promotionMoney2']");
                if (promotionType == "限时满减") {
                    if (parseFloat(promotionMoney1.val()) == 0) {
                        layer.tips("金额不能为0.00", promotionMoney1, {
                            tips: [1, '#2B2B2B'],
                            time: 2000
                        });
                        $(promotionMoney1).val('');
                        $(promotionMoney1).focus();
                        return false;
                    }
                    if (parseFloat(promotionMoney2.val()) == 0) {
                        layer.tips("金额不能为0", promotionMoney2, {
                            tips: [1, '#2B2B2B'],
                            time: 2000
                        });
                        $(promotionMoney2).val('');
                        $(promotionMoney2).focus();
                        return false;
                    }
                    if (parseFloat(promotionMoney1.val()) <= parseFloat(promotionMoney2.val())) {
                        layer.tips("满减价不能大于消费金额", promotionMoney2, {
                            tips: [1, '#2B2B2B'],
                            time: 2000
                        });
                        $(promotionMoney2).val('');
                        $(promotionMoney2).focus();
                        return false;
                    }
                }
                for (var j = i + 1; j < promotionMoney1List.length; j++) {
                    var promotionMoney1ListJ = $(promotionMoney1List[j])
                    if (parseFloat(promotionMoney1.val()) == parseFloat(promotionMoney1ListJ.val())) {
                        layer.tips("不能是相同的条件", promotionMoney1ListJ.parent(), {
                            tips: [1, '#2B2B2B'],
                            time: 3000
                        });
                        promotionMoney1ListJ.focus();
                        return false;
                    }
                }
            }
            $("#promotionCreateForm").ajaxSubmit({
                type: 'POST',
                url: "insertPromotion",
                // async: false,
                data: {
                    'type': promotionType
                },
                dataType: 'json',
                success: function (result) {
                    if (result.code == true) {
                        readonly();
                        $("#promotionCreateTableDiv").attr("style", "padding:12px; background-color: #F2F2F2;display:block");
                        renderTable('promotionCreateTable', 'getPromotionWares', result.promotionId, result.type);
                    } else {
                        layer.msg(result.msg);
                    }
                },
                // clearForm: true,
                // resetForm: true
            });
            return false;
        });
        //活动管理表格查询
        element.on('tab(docDemoTabBrief)', function (data) {
            if ($(this).html() == "活动管理") {
                // $("#promotionInfoSearchForm").submit();
                table.render({
                    elem: "#promotionInfoSearchTable"
                    , url: "promotionInfoSearch"
                    , method: "post"
                    , response: {
                        statusCode: true
                    }
                    , defaultToolbar: []
                    , cellMinWidth: 90
                    , cols: [[
                        {field: 'sorts', title: '序号', width: 60, templet: '#sort', align: 'center'}
                        // , {field: 'id', title: '活动编号', align: 'center',width:110}
                        , {field: 'name', title: '活动名称', align: 'center', width: 110}
                        , {field: 'type', title: '活动类型', align: 'center', width: 110}
                        , {field: 'describe', title: '活动说明', align: 'center', width: 110}
                        , {field: 'startDate', title: '开始时间', sort: true, align: 'center', width: 110}
                        , {field: 'endDate', title: '结束时间', sort: true, align: 'center', width: 110}
                        , {
                            field: 'status', title: '活动状态', align: 'center',
                            templet: function (d) {
                                if (d.status == "进行中") {
                                    return '<span style="color:#13CE67;">' + d.status + '</span>'
                                }
                                if (d.status == "未开始") {
                                    return '<span style="color:#1E9FFF;">' + d.status + '</span>'
                                }
                                if (d.status == "已结束") {
                                    return '<span style="color:#D92E2E;">' + d.status + '</span>'
                                }
                            }
                        }
                        , {field: 'creatorName', title: '创建人', align: 'center'}
                        , {
                            field: 'tool', title: '操作', align: 'center', width: 120,
                            templet: function (d) {
                                if (d.status == "未开始" || d.status == "进行中") {
                                    return '<span style="text-decoration:underline;cursor:pointer;color:#4BB2FF" lay-event="promotionDetails">详情</span>'
                                        + '<span style="margin-left:10px;text-decoration:underline;cursor:pointer;color:#FCC430" lay-event="endPromotionInfoSearch">结束</span>'
                                }
                                if (d.status == "已结束") {
                                    return '<span style="text-decoration:underline;cursor:pointer;color:#4BB2FF" lay-event="promotionDetails">详情</span>'
                                        + '<span style="margin-left:10px;text-decoration:underline;cursor:pointer;color:#D92E2E" lay-event="delPromotionInfoSearch">删除</span>'
                                }
                            }
                        }

                    ]]
                    , page: true
                    , id: "promotionInfoSearchTableRender"
                });
            }
            if ($(this).html() != "活动详情") {
                $("#promotionDetailsTab").addClass("layui-hide");
            }
        });
        form.on('submit(promotionInfoSearchForm)', function () {
            var page = $(".layui-laypage-em").next().html();
            var limit = $(".layui-laypage-limits").find("option:selected").val();
            if (page == undefined) {
                page = 1;
            }
            if (limit == undefined) {
                limit = 10;
            }
            $("#promotionInfoSearchForm").ajaxSubmit({
                type: 'POST',
                url: "promotionInfoSearch",
                data: {
                    page: page,
                    limit: limit,
                },
                // async: false,
                dataType: 'json',
                success: function (result) {
                    table.reload('promotionInfoSearchTableRender', {
                        url: null
                        , data: result.data
                        , page: {
                            curr: 1 //重新从第 1 页开始
                        }
                    });
                },
            });
            return false;
        });
        //自定义重置按钮，解决表不刷新
        $("#promotionInfoReset").click(function () {
            $("#promotionInfoSearchForm")[0].reset();
            $("#promotionInfoSearchForm").submit();
        });
        form.on('select()', function (data) {
            $("#promotionInfoSearchForm").submit();
        });
        table.on('tool(promotionCreateTable)', function (obj) {
            switch (obj.event) {
                case  'promotionWaresAdd':
                    $.ajax({
                        url: 'insertPromotionWares',
                        type: "POST",
                        data: {
                            "waresId": obj.data.id,
                            "promotionId": obj.data.expiryDate
                        },
                        dataType: "json",
                        // async: false,
                        success: function (result) {
                            if (result.code == true) {
                                table.reload('promotionCreateTableRender', {
                                    page: {
                                        curr: 1 //重新从第 1 页开始
                                    }
                                });
                            } else {
                                layer.msg(result.msg);
                            }
                        },
                    });
                    break;
                case  'promotionWaresDel':
                    $.ajax({
                        async: false,
                        url: 'deletePromotionWares',
                        type: "POST",
                        data: {
                            "waresId": obj.data.id,
                            "promotionId": obj.data.expiryDate
                        },
                        dataType: "json",
                        success: function (result) {
                            if (result.code === true) {
                                table.reload('promotionCreateTableRender', {
                                    page: {
                                        curr: 1 //重新从第 1 页开始
                                    }
                                });
                            } else {
                                layer.msg(result.msg);
                            }
                        },
                    });
                    break;
            }
        });
        table.on('tool(promotionInfoSearchTable)', function (obj) {
            if (obj.event === "endPromotionInfoSearch" || obj.event == "delPromotionInfoSearch") {
                layer.confirm('您确定要结束/删除活动？', function (index) {
                    layer.close(index);
                    $.ajax({
                        url: 'promotionInfoTool',
                        type: "POST",
                        data: {
                            "promotionId": obj.data.id,
                            "toolType": obj.event,
                        },
                        dataType: "json",
                        success: function (result) {
                            if (result.code == true) {
                                $("#promotionInfoSearchForm").submit();
                            } else {
                                layer.msg(result.msg);
                            }
                        },
                    });
                });
            }
            if (obj.event === "promotionDetails") {
                $.ajax({
                    url: 'showPromotionDetails',
                    type: "POST",
                    data: {
                        "promotionId": obj.data.id,
                    },
                    dataType: "json",
                    success: function (result) {
                        if (result.code == true) {
                            $("#promotionDetailsTab").removeClass("layui-hide");
                            $("#promotionDetailsTab").trigger("click");
                            let showPromotionInfo = $("#showPromotionInfo label");
                            showPromotionInfo.each(function () {
                                if ($(this).text().search("活动名称") != -1) {
                                    $(this).text("");
                                    $(this).append("活动名称：" + obj.data.name);
                                }
                                if ($(this).text().search("活动说明") != -1) {
                                    $(this).text("");
                                    $(this).append("活动说明：" + obj.data.describe);
                                }
                                if ($(this).text().search("活动类型") != -1) {
                                    $(this).text("");
                                    $(this).append("活动类型：" + obj.data.type);
                                }
                                if ($(this).text().search("活动状态") != -1) {
                                    $(this).text("");
                                    $(this).append("活动状态：" + obj.data.status);
                                }
                                if ($(this).text().search("活动日期") != -1) {
                                    $(this).text("");
                                    $(this).append("活动日期：" + obj.data.startDate + " - " + obj.data.endDate);
                                }
                                if ($(this).text().search("促销时段") != -1) {
                                    $(this).text("");
                                    $(this).append("活动时段：" + obj.data.startTime + " - " + obj.data.endTime);
                                }
                            });
                            let showPromotionRule = $("#showPromotionRule .layui-inline");
                            showPromotionRule.empty();
                            for (let i = 0; i < result.ruleData.length; i++) {
                                if (result.ruleData[i].promotion_type == "限时满减") {
                                    showPromotionRule.append(' <div class="layui-form-item"><label class="layui-form-label myTable">满' + result.ruleData[i].first + '元，减' + result.ruleData[i].second + '元。</label></div>');
                                }
                                if (result.ruleData[i].promotion_type == "限时折扣") {
                                    showPromotionRule.append(' <div class="layui-form-item"><label class="layui-form-label myTable">满' + result.ruleData[i].first + '元，打' + result.ruleData[i].second + '折。</label></div>');
                                }
                                if (result.ruleData[i].promotion_type == "特价商品") {
                                    showPromotionRule.append(' <div class="layui-form-item"><label class="layui-form-label myTable">商品ID - 名称：' + result.ruleData[i].first + '，特价：' + result.ruleData[i].second + '元。</label></div>');
                                }
                                if (result.ruleData[i].promotion_type == "特价分类") {
                                    showPromotionRule.append(' <div class="layui-form-item"><label class="layui-form-label myTable">分类名称：' + result.ruleData[i].first + '，折扣：' + result.ruleData[i].second + '折。</label></div>');
                                }
                            }
                        } else {
                            layer.msg(result.msg);
                        }
                    },
                    error: function () {
                        layer.alert("请稍后再试");
                    }
                });
            }
        });
        $(".promotionInSearchByIdOrName").click(function () {
            var btns = $(this);
            var waresIdOrName = btns.prev().val();
            btns.prop("disabled", true);
            if (!isEmpty(waresIdOrName)) {
                layer.open({
                    type: 1,
                    title: "待选商品",
                    skin: 'layui-layer-rim',//加边框
                    // area: ['','580px'],
                    // offset: ['0', '400px'],
                    content: '<table class="layui-disabled" id="promotionWaresSearchByIdTable" lay-filter="promotionWaresSearchByIdTable"></table>',
                    btn: ['确认', '取消'],
                    success: function (layero, index) {
                        table.render({
                            elem: "#promotionWaresSearchByIdTable"
                            , url: 'getPromotionWaresById'
                            , method: "post"
                            , response: {
                                statusCode: true
                            }
                            , where: {waresIdOrName: waresIdOrName}
                            , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                            , cols: [[
                                {
                                    field: 'radio', align: 'center', width: 80,
                                    templet: function (d) {
                                        return '<input type="radio" name="layTableRadio_2" lay-type="layTableRadio">' +
                                            '<div class="layui-unselect layui-form-radio">' +
                                            '<i class="layui-anim layui-icon"></i><div></div></div>'
                                    }
                                }
                                , {field: 'sorts', title: '序号', width: 80, templet: '#sort', align: 'center'}
                                , {field: 'id', title: '编号', width: 80, align: 'center'}
                                , {field: 'name', title: '名称', width: 100, align: 'center'}
                                , {field: 'category', title: '分类', align: 'center', width: 200}

                            ]]
                            , page: true
                            , id: "promotionWaresSearchByIdRender"
                        });
                        // alert($(layero).height())
                        layer.style(index, {
                            // top: ($(window).height() - $(layero).height()) / 2,
                            top: 0,
                            left: ($(window).width() - $(layero).width()) / 2
                        });
                    },
                    yes: function (index, layero) {
                        var checkStatusData = table.checkStatus('promotionWaresSearchByIdRender').data;
                        // btns.prev().html("[" + checkStatusData[0].id + "]" + checkStatusData[0].name);
                        if (!isEmpty(checkStatusData)) {
                            btns.prev().val(checkStatusData[0].id + " - " + checkStatusData[0].name);
                        } else {
                            btns.prev().val("");
                        }
                        layer.close(index);
                    },
                });
            } else {
                layer.tips("不能为空", btns.prev(), {
                    tips: [1, '#2B2B2B'],
                    time: 2000
                });
            }
            btns.prop("disabled", false);
        });

        function renderTable(elem, url, promotionId, type) {
            let endDate = $("#promotionDate").val().split(' - ')[1];
            let data = [];
            if (type == "特价分类") {
                var inputs = $('select[name="promotionMoney1"]');
            } else {
                var inputs = $('input[name="promotionMoney1"]');
            }
            inputs.each(function () {
                data.push($(this).val());
            });
            table.render({
                elem: "#" + elem
                , url: url
                , method: "post"
                , response: {
                    statusCode: true
                }
                , where: {endDate: endDate, promotionId: promotionId, data: data.toString()}
                , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                , cols: [[
                    {field: 'sorts', title: '序号', width: 60, event: "checkChange", templet: '#sort', align: 'center'}
                    , {field: 'id', title: '商品条码', width: 90, event: "checkChange", align: 'center'}
                    , {field: 'name', title: '名称', event: "checkChange", align: 'center'}
                    , {field: 'category', title: '分类', event: "checkChange", align: 'center'}
                    , {
                        field: 'price', title: '原售价(元)', event: "checkChange", align: 'center', templet: function (d) {
                            return d.price.toFixed(2);
                        }
                    }
                    , {
                        field: 'status', title: '参与状态', event: "checkChange", align: 'center',
                        templet: function (d) {
                            if (d.status === 1) {
                                return '<span style="color:#13CE67;">已参与</span>'
                            }
                            if (d.status === 0) {
                                return '<span style="color:#D92E2E;">未参与</span>'
                            }
                        }
                    }
                    , {
                        field: 'tool', title: '操作', align: 'center'
                        , templet: function (d) {
                            if (d.status === 1) {
                                return '<a lay-event="promotionWaresDel" style="color:#D92E2E;text-decoration:underline;cursor:pointer">移出活动</a>'
                            }
                            if (d.status === 0) {
                                return '<a lay-event="promotionWaresAdd" style="color:#338BFF;text-decoration:underline;cursor:pointer">加入活动</a>'
                            }
                        }
                    }
                ]]
                , page: true
                , id: elem + "Render"
            });
        }

        function readonly() {
            $('#addNewAgain').attr('class', 'layui-btn layui-btn-normal');
            $('#addNewAgain').attr('disabled', false);
            $('#submit').attr('class', 'layui-btn layui-btn-disabled');
            $('#submit').attr('disabled', "disabled");
            $('#reset').attr('class', 'layui-btn layui-btn-disabled');
            $('#reset').attr('disabled', "disabled");
            $('.promotionRuleAddBtn').attr('disabled', "disabled");
            $('.promotionRuleAddBtn').attr('class', 'layui-btn layui-btn-disabled');
            $('.promotionRuleDelBtn').attr('disabled', "disabled");
            $('.promotionRuleDelBtn').attr('class', 'layui-btn layui-btn-disabled');
            $('input,select,textarea', $('form[id="promotionCreateForm"]')).prop('readonly', true);
        }
    });
});

